/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package kotionokyurievna.gmail.com.circlebuffer.logic;

/**
 *
 * @author Kateryna_Reznik
 */
public class CircularBuffer {
    private int buffer[];
    private boolean empty;
    private boolean full;
    private int currentRead;
    private int currentWrite;
    private int length;
    private int currentSize;
    
    public CircularBuffer( int length ){
        setBuffer(length);
        currentRead = 0;
        currentWrite = 0;
        currentSize = 0;
        empty = true;
        full = false;
    }
    
    public void setBuffer( int length ){
        if ( length > 0 ){
            buffer = new int[length];
            this.length = length;
        }
        else{
            throw new IllegalArgumentException(" length must be > 0");
        }
    }
    
    public synchronized void put( int item ){
        if (full) {
            try { 
                wait();
            } 
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        buffer[currentWrite] = item;
        currentSize++;
        currentWrite = (currentWrite+1)%length;
        empty = false;
        if ( currentSize == length ){
            full = true;
        }
        notifyAll();
    }
    
    public synchronized String get(){
        if (empty) {
            try {
                wait();
            } 
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String returnValue = buffer[currentRead] + " " + currentRead;
        currentSize--;
        currentRead = (currentRead+1)%length;
        full = false;
        if ( currentSize == 0 ){
            empty = true;
        }
        notifyAll();
        return returnValue;
        
    }
        
}
